package com.whatech.mall.marketing.mq.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.whatech.mall.marketing.model.dto.messaging.OrderAddBonusMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 订单消息消费者。
 */
@Slf4j
@Component
public class OrderMessageConsumer {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 处理下单加积分消息。
     *
     * @param message 消息体
     * @param headers 消息Header
     * @param channel 手工签收（acknowledge-mode: manual）时需要用到
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "order-queue", durable = "true"),
            exchange = @Exchange(value = "order-exchange", durable = "true", type = "topic"),
            key = "order.addBonus"
    ))
    @RabbitHandler
    public void handleAddBonusMessage(@Payload String message,
                         @Headers Map<String , Object> headers,
                         Channel channel) throws Exception {
        log.info("Receive Message: {}", message);
        OrderAddBonusMessageDTO messageDTO = objectMapper.readValue(message, OrderAddBonusMessageDTO.class);
        log.info("OrderId: {}", messageDTO.getOrderId());

        // 手工签收消息
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
    }

}
